package com.google.code.ccr4j;

import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * Formatter for the rather obscure Date format that's used throughout the CCR
 */
public class ISO8601DateFormat extends DateFormat {


	private static final long serialVersionUID = 1L;
	private SimpleDateFormat simpleDateFormat =
            new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");

	@Override
	public StringBuffer format(Date date, StringBuffer toAppendTo,
			FieldPosition fieldPosition) {
		StringBuffer result = simpleDateFormat.format(date, toAppendTo, fieldPosition);
		
		if (result.toString().endsWith("0000")) {
			return new StringBuffer(result.substring(0, result.length() - 5))
                    .append("Z");
		} else {
			return new StringBuffer(result.substring(0, result.length() - 2))
                    .append(":").append(result.substring(result.length() - 2));
		}
	}

	@Override
	public Date parse(String source, ParsePosition pos) {
		if (source.endsWith("Z")) {
			source = source.substring(0, source.length() - 1) + "+0000";
		} else {
			source = source.substring(0, source.length() - 3) +
                    source.substring(source.length() - 2);
		}
		
		return simpleDateFormat.parse(source, pos);
	}
	
	@Override 
	public boolean equals(Object o) {
		if (o instanceof ISO8601DateFormat) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public int hashCode() {
		return 1;
	}
	
	/**
	* {@inheritDoc}
	*/
	@Override
	public void setTimeZone(TimeZone zone) {
		simpleDateFormat.setTimeZone(zone);
	}
}
